package com.auto.base.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auto.base.mapper.SysAccessoryMapper;
import com.auto.base.pojo.SysAccessory;
import com.auto.base.pojo.SysAccessoryExample;
import com.auto.base.pojo.SysAccessoryExample.Criteria;
import com.auto.base.service.SysAccessoryService;
import com.auto.common.SessionInfo;
import com.auto.util.MyJsonConfig;
import com.base.callback.MapperCallBack;
import com.base.common.CommonConstants;
import com.base.model.interfaze.FieldAppendAbstract;
import com.base.model.interfaze.FieldAppendArray;
import com.base.model.interfaze.MapperCallBackAdapter;
import com.base.util.JUtil;
import com.base.util.MapperUtil;
import com.base.util.Page;


@Transactional
@Service
@Scope("prototype")
public class SysAccessoryServiceImpl implements SysAccessoryService {
	@Resource 
	public SqlSessionTemplate sqlSession; 
	@Resource
	private SysAccessoryMapper mapper;
	private SqlSession session;

	/**
	 * 单个数据查询
	 * 
	 * @param record
	 * @param callback
	 * @return
	 */
	@Override
	public SysAccessory findSysAccessory(SysAccessory record, MapperCallBack callback) throws Exception {
		List<SysAccessory> records = listSysAccessory(record, null, new Page(0, 1), callback);
		if (null != records && records.size() > 0) {
			return records.get(0);
		}
		return null;
	}

	/**
	 * 单个数据查询,字段并关联外键值
	 * 
	 * @param record
	 * @param callback
	 * @return
	 */
	@Override
	public JSONObject findSysAccessoryAndFkText(SysAccessory record, MapperCallBack callback, FieldAppendArray appendArray) throws Exception {
		SysAccessory rec = findSysAccessory(record, callback);
		JSONObject jsonobj = null;
		if (null != rec) {
			//
			jsonobj = JSONObject.fromObject(rec,MyJsonConfig.JSON_CFG);
			// 遍历
			for (FieldAppendAbstract fieldAppend : appendArray) {
				// 属性名称
				String fieldName = fieldAppend.getFieldName();
				// 列表值
				Object listVal = fieldAppend.listValues(MapperUtil.getFiledVals(rec, fieldName));
				// 外键值
				Object oldVal = jsonobj.get(fieldName);
				// 最终返回值
				Object finalVal = fieldAppend.getValue(listVal, oldVal);
				//
				jsonobj.put(fieldAppend.getFieldName() + fieldAppend.getFieldSuffix(), finalVal);
			}
		}
		return null==jsonobj?new JSONObject():jsonobj;
	}

	/**
	 * 根据模型查找信息
	 * 
	 * @param 模型
	 * @page 页面(不分页,则传null)
	 * @orderByClause 排序(不需,则传null)
	 * @return 对象
	 * @throws Exception
	 */
	@Override
	public List<SysAccessory> listSysAccessory(SysAccessory record, String orderByClause, Page page, MapperCallBack callback) throws Exception {
		if(null == callback) callback = new MapperCallBackAdapter();
		//
		callback.doRecord(record);
		//
		SysAccessoryExample example = new SysAccessoryExample();
		// 去掉重复结果集
		example.setDistinct(true);
		// 分页
		if (null != page) {
			example.setPage(page);
		}
		// 排序
		if (!JUtil.isNull(orderByClause)) {
			example.setOrderByClause(orderByClause);
		}
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		//
		callback.doExample(example);
		// 构建查询条件
		MapperUtil.builderCriteria(criteria, record);
		//
		callback.doCriteria(criteria);
		if (null != page) {
			// 总条数
			int count = mapper.countByExample(example);
			page.setCount(count);
		}
		// 返回查询记录
		return mapper.selectByExample(example);
	}

	/**
	 * 查询,字段并关联外键值
	 * 
	 * @param record
	 * @param orderByClause
	 * @param page
	 * @param callback
	 * @param appendArray
	 * @return
	 * @throws Exception
	 */
	@Override
	public JSONArray listSysAccessoryAndFkText(SysAccessory record, String orderByClause, Page page, MapperCallBack callback, FieldAppendArray appendArray) throws Exception {
		// 属性,对应表,对应表字段
		List<SysAccessory> records = listSysAccessory(record, orderByClause, page, callback);
		//
		JSONArray array = JSONArray.fromObject(records,MyJsonConfig.JSON_CFG);
		//
		int size = array.size();
		//
		for (FieldAppendAbstract fieldAppend : appendArray) {
			List<String> oldFieldVals = MapperUtil.getFiledVals(records, fieldAppend.getFieldName());
			Object listVal = fieldAppend.listValues(oldFieldVals);
			for (int i = 0; i < size; i++) {
				//
				JSONObject jsonobj = array.getJSONObject(i);
				//
				Object oldVal = jsonobj.get(fieldAppend.getFieldName());
				//
				Object finalVal = fieldAppend.getValue(listVal, oldVal);
				//
				jsonobj.put(fieldAppend.getFieldName() + fieldAppend.getFieldSuffix(), finalVal);
			}
		}
		return array;
	}


	/**
	 * 新增数据
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public int insertSysAccessory(SysAccessory record) throws Exception {
		// 执行操作
		int res = mapper.insertSelective(record);
		// 抛出异常
		if (res <= 0)
			throw new RuntimeException("SysAccessory表新增数据失败");
		return record.getId();
	}

	/**
	 * 物理删除数据
	 * 杨浩
	 * @param  pks
	 * @throws Exception
	 */
	@Override
	public void dropSysAccessory(String pks) throws Exception {
		if (JUtil.isNull(pks)) {
			throw new RuntimeException("删除主键不能为空");
		}
		SysAccessoryExample example = new SysAccessoryExample();
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		criteria.andIdIn(JUtil.splitToListInteger(pks));
		// 执行操作
		int res = mapper.deleteByExample(example);
		// 抛出异常
		if (res <= 0){
			throw new RuntimeException("SysAccessory表删除数据失败");
		}
	}

	/**
	 * 更新数据
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public void modifySysAccessory(SysAccessory record, MapperCallBack callback) throws Exception {

		callback.doRecord(record);
		//
		SysAccessoryExample example = new SysAccessoryExample();
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		//
		callback.doExample(example);
		//
		callback.doCriteria(criteria);
		//
		if (!criteria.isValid()) {
			throw new RuntimeException("更新必须要设置条件!");
		}
		// 执行操作
		int res = mapper.updateByExampleSelective(record, example);
		// 抛出异常
		if (res <= 0) {
			throw new RuntimeException("SysAccessory表更新数据失败");
		}

	}

	/**
	 * 更新数据
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public int modifySysAccessoryByPkSelective(SysAccessory record) throws Exception {
		// 执行操作
		int res = mapper.updateByPrimaryKeySelective(record);
		// 抛出异常
		if (res <= 0) {
			throw new RuntimeException("SysAccessory表更新数据失败");
		}
		return res;
	}

	/**
	 * 更新数据
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public void modifySysAccessoryByPk(SysAccessory record) throws Exception {
		// 执行操作
		int res = mapper.updateByPrimaryKey(record);
		// 抛出异常
		if (res <= 0) {
			throw new RuntimeException("SysAccessory表更新数据失败");
		}
	}

	/**
	 * 总条数
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public int countSysAccessory(SysAccessory record, MapperCallBack callback) throws Exception {
		if(null == callback) 
		{
			callback = new MapperCallBackAdapter();
		}
		//
		callback.doRecord(record);
		//
		SysAccessoryExample example = new SysAccessoryExample();
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		//
		callback.doExample(example);
		//
		callback.doCriteria(criteria);
		// 执行操作
		int res = mapper.countByExample(example);
		return res;
	}

	/**
	 * 总条数新增方法
	 * 
	 * @param record
	 * @throws Exception
	 */
	@Override
	public int countSysAccessory(SysAccessory record) throws Exception {

		MapperCallBack callback = new MapperCallBackAdapter();

		callback.doRecord(record);
		//
		SysAccessoryExample example = new SysAccessoryExample();
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		// 根据record重新构建查询条件
		MapperUtil.builderCriteria(criteria, record);
		// 执行操作
		int res = mapper.countByExample(example);
		return res;
	}

	/**
	 * 逻辑删除数据最新方法
	 * 杨浩
	 * @param pks
	 * @throws Exception
	 */
	@Override
	public void deleteSysAccessory(String pks) throws Exception {
		if (JUtil.isNull(pks)) {
			throw new RuntimeException("逻辑删除主键不能为空");
		}
		SysAccessoryExample example = new SysAccessoryExample();
		// 设置查询条件
		Criteria criteria = example.createCriteria();
		criteria.andIdIn(JUtil.splitToListInteger(pks));
		SysAccessory record = new SysAccessory();
		record.setEnabled(1);
		// 执行操作
		int res = mapper.updateByExampleSelective(record,example);
		// 抛出异常
		if (res <= 0){
			throw new RuntimeException("SysAccessory表逻辑删除数据失败");
		}
	}

	/**
	 * 对导入进来的数据进行入库处理 
	 * @param list
	 * @throws Exception
	 */
	@Override
	public void inputExcelData(Map<String,Object> result) throws Exception {
		List<SysAccessory> list  = (List<SysAccessory>)result.get(CommonConstants.INPUT_RESULTKEY);
		if(!list.isEmpty()){
			for(SysAccessory record: list){
				this.insertSysAccessory(record);
			}
		}
	}

	/**
	 * 批量导入处理
	 * @param list
	 * @param request
	 * @throws Exception
	 */
	public void insertBeatch(List<SysAccessory> list,SessionInfo sessionInfo)
			throws Exception {
		if(null == list || list.isEmpty()){
			throw new RuntimeException("导入数据为空!");
		}
		try{
			session = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			SysAccessoryMapper m = session.getMapper(SysAccessoryMapper.class);
			try{
				int length = list.size(),maxSize = length;
				int currentValue  = 10;
				Date date = new Date();
				//Integer addUserId = sessionInfo.getSysUser().getId();
				//String addUserName = sessionInfo.getSysUser().getUserName();
				while(length > 0){
					SysAccessory record  = list.get(length-1);
					record.setAddTime(date.getTime());
					//record.setAddUser(addUserId);
					record.setUpdateTime(record.getAddTime());
					//record.setLastUpdateUser(addUserId);
					m.insertSelective(record);
					length -- ;
				}
				session.commit();
				session.clearCache();	
			}catch(Exception e){
				session.rollback();//回滚
				throw e;
			}finally{
				session.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			//可以加入日志记录
			throw e;	
		}
	}

	/**
	 * 批量修改
	 * @param list
	 * @param request
	 * @throws Exception
	 */
	public void modifyBeatch(List<SysAccessory> list,SessionInfo sessionInfo)
			throws Exception {
		if(null == list || list.isEmpty()){
			throw new RuntimeException("导入数据为空!");
		}
		try{
			session = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			SysAccessoryMapper m = session.getMapper(SysAccessoryMapper.class);
			try{
				int length = list.size(),maxSize = length;
				int currentValue  = 10;
				Date date = new Date();
				//Integer addUserId = sessionInfo.getSysUser().getId();
				//String addUserName = sessionInfo.getSysUser().getUserName();
				while(length > 0){
					SysAccessory record  = list.get(length-1);
					record.setUpdateTime(date.getTime());
					//record.setAddUser(addUserId);
					//record.setLastUpdateUser(addUserId);
					m.updateByPrimaryKeySelective(record);
					length -- ;
				}
				session.commit();
				session.clearCache();	
			}catch(Exception e){
				session.rollback();//回滚
				throw e;
			}finally{
				session.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			//可以加入日志记录
			throw e;	
		}
	}
}
